"""
商品相关服务
"""
from app.models.product import Product, ProductSpecification, ProductVariant, ProductStatus
from app.extensions import db
from app.utils.errors import NotFoundError, ValidationError

class ProductService:
    """商品服务类"""
    
    @staticmethod
    def get_products(page=1, per_page=20, name=None, sort_by='id', sort_order='asc'):
        """获取商品列表"""
        query = Product.query
        
        # 过滤
        if name:
            query = query.filter(Product.name.ilike(f'%{name}%'))
        
        # 排序
        if sort_order == 'desc':
            query = query.order_by(getattr(Product, sort_by).desc())
        else:
            query = query.order_by(getattr(Product, sort_by).asc())
        
        # 分页
        pagination = query.paginate(page=page, per_page=per_page)
        
        return pagination
    
    @staticmethod
    def get_product(product_id):
        """获取商品详情"""
        product = Product.query.get(product_id)
        
        if not product:
            raise NotFoundError("商品不存在")
        
        return product
    
    @staticmethod
    def create_product(data):
        """创建商品"""
        try:
            # 创建商品
            product = Product(
                name=data.get('name'),
                description=data.get('description'),
                price=data.get('price'),
                stock=data.get('stock', 0),
                sku=data.get('sku'),
                status=data.get('status', ProductStatus.ACTIVE.value)
            )
            
            # 设置图片
            if 'images' in data:
                product.image_list = data.get('images')
            
            db.session.add(product)
            
            # 创建规格
            if 'specifications' in data:
                for spec_data in data['specifications']:
                    spec = ProductSpecification(
                        name=spec_data.get('name'),
                        product=product
                    )
                    if 'options' in spec_data:
                        spec.option_list = spec_data.get('options')
                    db.session.add(spec)
            
            # 创建变体
            if 'variants' in data:
                for variant_data in data['variants']:
                    variant = ProductVariant(
                        sku=variant_data.get('sku'),
                        price=variant_data.get('price'),
                        stock=variant_data.get('stock', 0),
                        specifications=variant_data.get('specifications', {}),
                        product=product
                    )
                    db.session.add(variant)
            
            db.session.commit()
            return product
            
        except Exception as e:
            db.session.rollback()
            raise ValidationError(f"创建商品失败: {str(e)}")
    
    @staticmethod
    def update_product(product_id, data):
        """更新商品"""
        product = Product.query.get(product_id)
        
        if not product:
            raise NotFoundError("商品不存在")
        
        try:
            # 更新基本信息
            if 'name' in data:
                product.name = data.get('name')
            if 'description' in data:
                product.description = data.get('description')
            if 'price' in data:
                product.price = data.get('price')
            if 'stock' in data:
                product.stock = data.get('stock')
            if 'sku' in data:
                product.sku = data.get('sku')
            if 'status' in data:
                product.status = data.get('status')
            if 'images' in data:
                product.image_list = data.get('images')
            
            db.session.commit()
            return product
            
        except Exception as e:
            db.session.rollback()
            raise ValidationError(f"更新商品失败: {str(e)}")
    
    @staticmethod
    def delete_product(product_id):
        """删除商品"""
        product = Product.query.get(product_id)
        
        if not product:
            raise NotFoundError("商品不存在")
        
        try:
            db.session.delete(product)
            db.session.commit()
            return {"msg": "商品删除成功"}
            
        except Exception as e:
            db.session.rollback()
            raise ValidationError(f"删除商品失败: {str(e)}")
    
    @staticmethod
    def add_specification(product_id, name, options=None):
        """添加商品规格"""
        product = Product.query.get(product_id)
        
        if not product:
            raise NotFoundError("商品不存在")
        
        try:
            spec = ProductSpecification(
                name=name,
                product=product
            )
            
            if options:
                spec.option_list = options
                
            db.session.add(spec)
            db.session.commit()
            return spec
            
        except Exception as e:
            db.session.rollback()
            raise ValidationError(f"添加规格失败: {str(e)}")
    
    @staticmethod
    def add_variant(product_id, data):
        """添加商品变体"""
        product = Product.query.get(product_id)
        
        if not product:
            raise NotFoundError("商品不存在")
        
        try:
            variant = ProductVariant(
                sku=data.get('sku'),
                price=data.get('price'),
                stock=data.get('stock', 0),
                specifications=data.get('specifications', {}),
                product=product
            )
            
            db.session.add(variant)
            db.session.commit()
            return variant
            
        except Exception as e:
            db.session.rollback()
            raise ValidationError(f"添加变体失败: {str(e)}") 